package com.tanhua.server.interceptor;

import com.tanhua.server.pojo.User;
import com.tanhua.server.service.UserService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class LogInterceptor implements HandlerInterceptor {
    @Autowired
    RocketMQTemplate rocketMQTemplate;
    @Autowired
    private UserService userService;

@Component
public class LogInterceptor implements HandlerInterceptor {

    /**
     * 拦截所有的uri，然后将行为发送给mq
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        System.out.println(request.getRequestURI());

        //mq发送消息 时间+用户id+访问uri
        String uri = request.getRequestURI();
        long time = System.currentTimeMillis();

        //获取token
        String token = request.getHeader("Authorization");
        //调用UserService里面的验证token方法，校验token是否有效
        User user = userService.queryUserByToken(token);
        Long userId = user.getId();

        //封装到map中
        Map<String, Object> msg = new HashMap<>();
        msg.put("uri",uri);
        msg.put("time",time);
        msg.put("userId",userId);

        this.rocketMQTemplate.convertAndSend("tanhua-sso-server", msg);

    }
}
